const Promise = require("bluebird");
const jwt = require("jsonwebtoken");
const verify = Promise.promisify(jwt.verify);
const { secret } = require("../config/keys");

async function check(ctx, next) {
  const url = ctx.request.url;
  const method = ctx.request.method;

  // const whiteList = ['login', '/images']
  // 登录 不用检查
  // if (whiteList.some(v => url.includes(v))) await next();
  const whiteList = [
    {
      url: "/user",
      method: "POST",
    },
    {
      url: "/room/list/edit",
      method: "POST",
    },
  ];
  if (whiteList.some((v) => v.method === method && v.url === url)) {
    // 规定token写在header 的 'autohrization'
    let token = ctx.request.headers["authorization"];
    if (!token) {
      ctx.body = {
        code: 401,
        message: "token 已过期或者非法",
      };
      return;
    }
    token = token.replace("Bearer ", "");

    // 解码
    let payload = await verify(token, secret);
    let { time, timeout } = payload;
    let data = new Date().getTime();
    if (data - time <= timeout) {
      ctx.state.user = payload;
      // 未过期
      await next();
    } else {
      //过期
      ctx.body = {
        code: 401,
        message: "token 已过期",
      };
    }
  } else {
    // let token = ctx.request.headers["authorization"];
    // if(token) {
    //   let payload = await verify(token, secret);
    //   ctx.state.user = payload;
    // }

    // 未过期
    await next();
  }
}

module.exports = check;
